//
//  AVFoundationrExample.swift
//  SwiftCode
//
//  Created by 于虎拴 on 2023/2/17.
//  https://developer.apple.com/documentation/avfoundation

import Foundation
import AVFoundation
import AVKit

/// - Media assets
///   - 异步加载媒体数据
/// - Media reading and writing
///   - 将视频导出为其他格式
///   - 从视频资源创建图像
/// - Media playback
///   - 配置应用程序进行媒体播放
class AVFoundationExample: ListViewController {
  let urls = [
    "https://vd2.bdstatic.com/mda-mfb3uq1kxn4weuep/sc/cae_h264_nowatermark/1623487595425899483/mda-mfb3uq1kxn4weuep.mp4",
    "https://vd3.bdstatic.com/mda-nh7eucbs3exn4ahu/sc/cae_h264/1659971913882280362/mda-nh7eucbs3exn4ahu.mp4",
    "https://vd3.bdstatic.com/mda-pbj9mtwnpgbxcqn3/720p/h264/1676875747815412779/mda-pbj9mtwnpgbxcqn3.mp4"
  ]
  
  override func viewDidLoad() {
    super.viewDidLoad()
    
    // FIXME: 播放器没有。配置应用程序进行媒体播放
    let session = AVAudioSession.sharedInstance()
    try? session.setCategory(.playback, mode: .moviePlayback)
  }
  
  override func getItemCount() -> Int {
    data.count
  }
  
  override func getItem(_ indexPath: IndexPath) -> Item {
    data[indexPath.row]
  }
  
  private lazy var data: [Item] = [
    .init(title: "AVAsset property", description: "异步加载媒体数据", action: { [weak self] in
      self?.loadAsyncProperty()
    }),
    .init(title: "AVAssetImageGenerator", description: "从视频资源第 6 秒时创建图像", action: { [weak self] in
      self?.generateImage()
    }),
    .init(title: "AVPlayerViewController 本地视频", description: "系统播放器 m4v+present", action: { [weak self] in
      guard let self, let url = Bundle.main.url(forResource: "video", withExtension: "m4v") else { return }
      let player = AVPlayer(url: url)
      
      let controller = AVPlayerViewController()
      controller.player = player
      
      self.present(controller, animated: true)
    }),
    .init(title: "AVPlayerViewController 网络视频", description: "系统播放器 mp4+push", action: { [weak self] in
      guard let self, let url = URL(string: self.urls[2]) else { return }
      
      let player = AVPlayer(url: url)
      
      let controller = AVPlayerViewController()
      controller.player = player
      
      self.navigationController?.pushViewController(controller, animated: true)
    }),
    .init(title: "PlayerViewController 本地视频", description: "自定义播放器 m4v+present", action: { [weak self] in
      guard let self, let url = Bundle.main.url(forResource: "video", withExtension: "m4v") else { return }
      self.present(PlayerViewController(url), animated: true)
    }),
    .init(title: "PlayerViewController 网络视频", description: "自定义播放器 mp4+push", action: { [weak self] in
      guard let self, let url = URL(string: self.urls[0]) else { return }
      self.navigationController?.pushViewController(PlayerViewController(url), animated: true)
    })
  ]
}
